<script lang="ts" setup>
import type { SystemRoleApi } from '#/api/system/role';

import { computed, onMounted, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';
import { Search } from '@vben/icons';
import { usePreferences } from '@vben/preferences';

import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons-vue';
import { Button, Dropdown, Input, List, Menu, message } from 'ant-design-vue';

import { deleteRole, getSimpleRoleList } from '#/api/system/role';
import { $t } from '#/locales';

import Form from '../modules/form.vue';

const emit = defineEmits(['select']);
const { isDark } = usePreferences();

const roleList = ref<SystemRoleApi.Role[]>([]); // 所有角色数据

const searchValue = ref(''); // 搜索输入值

const loading = ref(false);

const selectedRoleId = ref<null | number>(null); // 当前选中的角色 ID

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

/** 根据搜索关键词实时过滤角色列表 */
const filteredList = computed(() => {
  const value = searchValue.value.trim().toLowerCase();
  return value
    ? roleList.value.filter((item) => item.name.toLowerCase().includes(value))
    : roleList.value;
});

/** 搜索框触发变化 */
function handleSearch(e: any) {
  searchValue.value = e.target.value;
}

/** 选中某个角色后更新状态并通知父组件 */
const handleSelect = (role: SystemRoleApi.Role) => {
  selectedRoleId.value = role.id;
  emit('select', role);
};

/** 新增角色按钮点击事件 */
function handleCreate() {
  formModalApi.setData(null).open();
}

/** 编辑角色按钮点击事件 */
function handleEdit(row: SystemRoleApi.Role) {
  formModalApi.setData(row).open();
}

/** 删除角色操作 */
async function handleDelete(row: SystemRoleApi.Role) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.name]),
    duration: 0,
  });
  try {
    await deleteRole(row.id!);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.name]),
    });
    loadRoleList();
  } finally {
    hideLoading();
  }
}

/** 加载角色列表并默认选中第一个角色 */
const loadRoleList = async () => {
  try {
    loading.value = true;
    const data = await getSimpleRoleList();
    roleList.value = data;
    if (data.length > 0) {
      selectedRoleId.value = data[0].id as number;
      emit('select', data[0]); // 默认选中第一个角色
    }
  } catch (error) {
    console.error('获取角色数据失败', error);
  } finally {
    loading.value = false;
  }
};

/** 页面挂载完成后加载角色列表 */
onMounted(() => {
  loadRoleList();
});
</script>
<template>
  <!-- 表单弹窗组件 -->
  <FormModal @success="loadRoleList()" />

  <div>
    <!-- 顶部操作区域：搜索 + 新增按钮 -->
    <div class="mb-3 flex items-center justify-between gap-2">
      <!-- 搜索框 -->
      <Input
        placeholder="搜索角色"
        allow-clear
        v-model:value="searchValue"
        @change="handleSearch"
        class="w-64"
      >
        <template #prefix>
          <Search class="size-4" />
        </template>
      </Input>

      <!-- 新增角色按钮 -->
      <Button
        type="primary"
        @click="handleCreate"
        class="flex items-center gap-1"
      >
        <PlusOutlined />
      </Button>
    </div>

    <!-- 角色列表 -->

    <List :data-source="filteredList" :loading="loading" :split="false">
      <template #renderItem="{ item }">
        <List.Item
          class="cursor-pointer px-1"
          :class="{
            'bg-blue-50': selectedRoleId === item.id && !isDark,
            'bg-gray-800': selectedRoleId === item.id && isDark,
            'hover:bg-gray-50': !isDark,
            'hover:bg-gray-800': isDark,
          }"
          @click="handleSelect(item)"
        >
          <!-- 每项的布局：名称 + 操作菜单 -->
          <div class="flex w-full items-center justify-between">
            <!-- 角色名 -->
            <span>{{ item.name }}</span>

            <!-- 操作下拉菜单 -->
            <Dropdown :trigger="['click']">
              <EllipsisOutlined
                class="cursor-pointer text-gray-500 hover:text-blue-500"
                @click.stop
              />
              <template #overlay>
                <Menu>
                  <Menu.Item
                    key="edit"
                    :disabled="!item.editable"
                    @click="handleEdit(item)"
                  >
                    修改
                  </Menu.Item>
                  <Menu.Item
                    key="delete"
                    danger
                    :disabled="!item.editable"
                    @click="handleDelete(item)"
                  >
                    删除
                  </Menu.Item>
                </Menu>
              </template>
            </Dropdown>
          </div>
        </List.Item>
      </template>
    </List>
  </div>
  <!-- 空数据提示 -->
  <div
    v-if="!loading && filteredList.length === 0"
    class="py-4 text-center text-gray-500"
  >
    暂无数据
  </div>
</template>
